import { ref, computed } from 'vue'
import { useIntersectionObserver, useIntervalFn } from '@vueuse/core'
import dayjs from 'dayjs'

export const useObserver = (apiFn) => {
  const list = ref([])
  const target = ref(null)
  const { stop } = useIntersectionObserver(
    // 监测的目标 可以是组件可以是dom
    target,
    ([{ isIntersecting }]) => {
      if (isIntersecting) {
        apiFn().then(({ result }) => {
          list.value = result
        })
        stop()
      }
    }
  )

  return { list, target }
}

/**
 *
 * @param {number} time 倒计时开始
 * @returns {object} {countTime, start, pause}
 */

export const useCountDown = (time = 60) => {
  const countTime = ref(0)

  // 事件封装
  const countTimeText = computed(() => {
    return dayjs.unix(countTime.value).format('mm分ss秒')
  })

  const { resume, pause } = useIntervalFn(() => {
    countTime.value--
    if (countTime.value <= 0) {
      pause()
    }
  }, 1000, { immediate: false })

  const start = (newTime) => {
    if (countTime.value === 0) {
      countTime.value = newTime || time
    }
    resume()
  }

  return { countTime, start, countTimeText, pause }
}
